/**
 * jquery.dropdown.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2012, Codrops
 * http://www.codrops.com
 */
;( function( $, window, undefined ) {

	'use strict';

	$.DropDown = function( options, element ) {
		this.$el = $( element );
		this._init( options );
	};

	// the options
	$.DropDown.defaults = {
		speed : 300,
		easing : 'ease',
		gutter : 0,
		// initial stack effect
		stack : true,
		// delay between each option animation
		delay : 0,
		// random angle and positions for the options
		random : false,
		// rotated [right||left||false] : the options will be rotated to thr right side or left side.
		// make sure to tune the transform origin in the stylesheet
		rotated : false,
		// effect to slide in the options. value is the margin to start with
		slidingIn : false,
		onOptionSelect : function(opt) { return false; }
	};

	$.DropDown.prototype = {

		_init : function( options ) {

			// options
			this.options = $.extend( true, {}, $.DropDown.defaults, options );
			this._layout();
			this._initEvents();
			
		},
		_layout : function() {

			var self = this;
			
			this.minZIndex = 1000;
			var value = this._transformSelect();
			this.opts = this.listopts.children( 'li' );
			this.optsCount = this.opts.length;
			this.size = { width : this.dd.width(), height : this.dd.height() };
			
			var elName = this.$el.attr( 'name' ), elId = this.$el.attr( 'id' ),eltext=$(this).text(),
				inputName = elName !== undefined ? elName : elId !== undefined ? elId : 'cd-dropdown-' + ( new Date() ).getTime();

			this.inputEl = $( '<input type="hidden" name="' + inputName + '" value="' + value + '" data-value="' + value +'"></input>' ).insertAfter( this.selectlabel );
			
			this.selectlabel.css( 'z-index', this.minZIndex + this.optsCount );
			this._positionOpts();
			if( Modernizr.csstransitions ) {
				setTimeout( function() { self.opts.css( 'transition', 'all ' + self.options.speed + 'ms ' + self.options.easing ); }, 25 );
			}

		},
		_transformSelect : function() {
			var divwidth='';
			var optshtml = '', selectlabel = '', value = -1;
			var name=this.$el.attr('name');
			this.$el.children( 'option' ).each( function() {

				var $this = $( this ),
					val = isNaN( $this.attr( 'value' ) ) ? $this.attr( 'value' ) : Number( $this.attr( 'value' ) ) ,
					classes = $this.attr( 'class' ),
					selected = $this.attr( 'selected' ),
					label = $this.text();

				if( val !== -1 ) {
					if(name=='analysisof'){
						divwidth=' style="width:540px;" ';
						var arrayof={'-1':'Choose your Analysis',itTalentpool:'Total talent pool available in IT Companies',compCount:'Total No. of IT Companies',
						cbAnalysis:'Salary Cost Analysis in IT Companies',itFulltocontract:'% of employees on contract role from total employees',itAttrition:'Attrition Analysis in IT Companies',
								itGendiversity:'Ratio of Male to Female employees',locoutper:'% local employees from total employees',industrialbodies:'State and city level Industrial Bodies',
								clgFinalstu:'Final year Students(2014 passout) in Colleges (Technology & Business)',clgCount:'Total No. of Colleges(Technology + Business)',
								intakeSum:'Total Intake Capacity in Coleeges(Technology + Business) in 2014/2015',
								utilizationSum:'Total Utilization of Intake seats in colleges(Technology + Business) in 2014/2015',
								utilizationperAverage:'% Utilization of Intake seats in colleges(Technology + Business) in 2014/2015',
								growthrate:'Intake (Techlogy + Business) growth rate from 2011 to 2014',
								placementperAverage:'% Placement for students passed out in 2013',placementPkg:'Salary package offered to students during placement in 2011 to 2014',
								locStuperaverage:'% of local students from total students (technology + students) in the colleges',
							    uniCount:'Total No of Universities providing Technology & Management Education',trainCount:'Total No of Training Institutes providing training on Technology skill'};

					optshtml += 
						classes !== undefined ? 
							'<li data-value="' + val + '"><span class="' + classes + '"><img src="/images/EC_Icons/'+$.trim(label.replace('%',''))+'.png" width="40" height="40" style="margin-right:10px;"><span class="title">' + label + '</span><span class="caption">'+arrayof[$this.attr( 'value' )]+'</span></span></li>' :
							'<li data-value="' + val + '"><span><div style="float:left;"><img src="/images/EC_Icons/'+$.trim(label.replace('%','').replace('/',''))+'.png" width="30" height="30" style="margin-right:10px;margin-top:5px;vertical-align:middle;"></div><div style="float:left;width:440px;"><label class="title">' + label + '</label><label class="caption1">'+arrayof[$this.attr( 'value' )]+'</label></div><div style="clear:both;"></div></span></li>';
					}else if(name=='analysisby'){
						divwidth=' style="width:380px;" ';
						var arrayby={'-1':'select',clgType:'Analysis by type(Tier I, Tier II, Tier III colleges)',clgCategory:'Analysis by Category(AICTE Approved, Autonomus, etc)Colleges',clgEdulevel:'Analysis by Level of Education(UG, PG, Diploma)',
								clgCourse:'Analysis by Courses(Eng., MBA, MCA)provided by colleges',clgStreamcluster:'Analysis by Stream (Computer Science, Electrical,Mechanical, etc)',clgStreamCN:'Computing(IT/Electrical), Non Computing(Mechanical/Chemical)',clgYoerange:'College Establishment Year (1950 to 1975, 1975 to 1980, etc)',
								clgIntakerange:'Range of the Intake Capacity (50 to 100, 100 to 200, etc)',clgUtilizationrange:'Range of Utilization (50 to 100, 100 to 200, etc)',
								clgUtilizationrangeper:'Utilization %  (50 to 60%, 60 to 75%, etc)',uniType:'Analysis by Uni. Type (Deemed, Central, Open, etc)',trainSkill:'Analysis by training offerings (Skill/Product, Web dev., Networking)',
								trainAuth:'Analysis by Type of Institute (Authorised, Unauthorised)',itHQCountry:'Analysis by HQ locations of the Companies (Country presence)',itComptype:'Analysis by type of companies (TIER I, Tier II & Tier III)',
								itTalentpoolwold:'Analysis by total talent pool available world-wide',itBusarea:'Analysis by Business Areas(R&D, IT Services & BPO)',itSkill:'Analysis by Skill/Function(SAP, PES, Oracle,etc)',indLevel:'Analysis by IT Body\'s operational limits (City level and State level',
								indIndustry:'Analysis by type(IT Bodies, Dev. Bodies, Traders, etc)'};
						optshtml += 
							classes !== undefined ? '<li data-value="' + val + '"><span class="' + classes + '">' + label + '</span></li>' :
								'<li data-value="' + val + '"><span><div style="width:350px;"><label class="title">' + label + '</label><label class="caption1">'+arrayby[$this.attr( 'value' )]+'</label></div></span></li>';

					}else{
						optshtml += 
							classes !== undefined ? 
								'<li data-value="' + val + '"><span class="' + classes + '">' + label + '</span></li>' :
								'<li data-value="' + val + '"><span>' + label + '</span></li>';
					}
				}

				if( selected ) {
					selectlabel = label;
					value = val;
				}

			} );

			this.listopts = $( '<ul/>' ).append( optshtml );
			this.selectlabel = $( '<span/>' ).append( selectlabel );
			this.dd = $( '<div class="cd-dropdown" id="'+this.$el.attr('name')+'"'+divwidth+'/>' ).append( this.selectlabel, this.listopts ).insertAfter( this.$el );
			this.$el.remove();

			return value;

		},
		_positionOpts : function( anim ) {

			var self = this;

			this.listopts.css( 'height', 'auto' );
			this.opts
				.each( function( i ) {
					$( this ).css( {
						zIndex : self.minZIndex + self.optsCount - 1 - i,
						top : self.options.slidingIn ? ( i + 1 ) * ( self.size.height + self.options.gutter ) : 0,
						left : 0,
						marginLeft : self.options.slidingIn ? i % 2 === 0 ? self.options.slidingIn : - self.options.slidingIn : 0,
						opacity : self.options.slidingIn ? 0 : 1,
						transform : 'none'
					} );
				} );

			if( !this.options.slidingIn ) {
				this.opts
					.eq( this.optsCount - 1 )
					.css( { top : this.options.stack ? 9 : 0, left : this.options.stack ? 4 : 0, width : this.options.stack ? this.size.width - 8 : this.size.width, transform : 'none' } )
					.end()
					.eq( this.optsCount - 2 )
					.css( { top : this.options.stack ? 6 : 0, left : this.options.stack ? 2 : 0, width : this.options.stack ? this.size.width - 4 : this.size.width, transform : 'none' } )
					.end()
					.eq( this.optsCount - 3 )
					.css( { top : this.options.stack ? 3 : 0, left : 0, transform : 'none' } );
			}

		},
		_initEvents : function() {
			
			var self = this;
			$(document).on("click", function (e) {
				 var container = $(".cd-dropdown");
				if (!container.is(e.target)&& container.has(e.target).length === 0)
					if(self.opened)
				self.close();
			});
			this.selectlabel.on( 'mousedown.dropdown', function( event ) {
				self.opened ? self.close() : self.open();
				return false;

			} );

			this.opts.on( 'click.dropdown', function() {
				if( self.opened ) {
					var opt = $( this );
					if(self.inputEl.attr('name')=='analysisof'){
						analysisofchange(opt.data( 'value' ));
						self.inputEl.attr( 'data-value',opt.find('.title').text()); 
					}
				else if(self.inputEl.attr('name')=='analysisby')
					self.inputEl.attr( 'data-value',opt.find('.title').text()); 
					else
						self.inputEl.attr( 'data-value',opt.text());
					self.options.onOptionSelect( opt );
					self.inputEl.val( opt.data( 'value' ) );
					self.selectlabel.html( opt.html() );
					self.close();
				}
			} );

		},
		open : function() {
			var self = this;
			this.dd.toggleClass( 'cd-active' );
			if(this.optsCount>4)
			this.listopts.css( 'height', '300' );
			else
			this.listopts.css( 'height', ( this.optsCount + 1 ) * ( this.size.height + this.options.gutter ) );
			this.opts.each( function( i ) {

				$( this ).css( {
					opacity : 1,
					top : self.options.rotated ? self.size.height + self.options.gutter : ( i + 1 ) * ( self.size.height + self.options.gutter ),
					left : self.options.random ? Math.floor( Math.random() * 11 - 5 ) : 0,
					width : self.size.width,
					marginLeft : 0,
					transform : self.options.random ?
						'rotate(' + Math.floor( Math.random() * 11 - 5 ) + 'deg)' :
						self.options.rotated ?
							self.options.rotated === 'right' ?
								'rotate(-' + ( i * 5 ) + 'deg)' :
								'rotate(' + ( i * 5 ) + 'deg)'
							: 'none',
					transitionDelay : self.options.delay && Modernizr.csstransitions ? self.options.slidingIn ? ( i * self.options.delay ) + 'ms' : ( ( self.optsCount - 1 - i ) * self.options.delay ) + 'ms' : 0
				} );

			} );
			this.opened = true;

		},
		close : function() {

			var self = this;
			this.dd.toggleClass( 'cd-active' );
			if( this.options.delay && Modernizr.csstransitions ) {
				this.opts.each( function( i ) {
					$( this ).css( { 'transition-delay' : self.options.slidingIn ? ( ( self.optsCount - 1 - i ) * self.options.delay ) + 'ms' : ( i * self.options.delay ) + 'ms' } );
				} );
			}
			this._positionOpts( true );
			this.opened = false;

		}

	}

	$.fn.dropdown = function( options ) {
		var instance = $.data( this, 'dropdown' );
		if ( typeof options === 'string' ) {
			var args = Array.prototype.slice.call( arguments, 1 );
			this.each(function() {
				instance[ options ].apply( instance, args );
			});
		}
		else {
			this.each(function() {
				instance ? instance._init() : instance = $.data( this, 'dropdown', new $.DropDown( options, this ) );
			});
		}
		return instance;
	};

} )( jQuery, window );
